package org.helldorado.companybuilder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import android.support.v4.app.Fragment;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import org.helldorado.companybuilder.R;

import com.haarman.supertooltips.ToolTip;
import com.haarman.supertooltips.ToolTipRelativeLayout;
import com.haarman.supertooltips.ToolTipView;
import com.haarman.supertooltips.ToolTipView.OnToolTipViewClickedListener;

//extended from compatibility Fragment for pre-HC fragment support
public class BodyFragment extends Fragment{
	private Map<Integer, Model> m_modelList;
	private List<ImageView> m_lifePointViews = new ArrayList<ImageView>();
   // onCreate
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
   }

   // onActivityCreated
   @Override
   public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
   }
   
   // onCreateView
   @Override
   public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fr_body,container,false);
      Activity act = getActivity();
	  Context ctx = (Context)act;
      m_modelList = ModelList.getInstance(ctx).getHashMap();
      return view;
   }
   
   private String formatStat(String stat, String statWounded)
   {
	   if (!statWounded.equalsIgnoreCase("-") && !statWounded.equalsIgnoreCase("0")) {
		   stat += " / " + statWounded;
	   }
	   
	   return stat;
   }
   private void setStatTable(Model model) {
	      TextView view = (TextView) getView().findViewById(R.id.modelNameTxt);
	      view.setText(model.getName());
	      TextView viewMVT = (TextView) getView().findViewById(R.id.textViewMVT);
	      viewMVT.setText(formatStat(model.MVT, model.MVTW));
	      TextView viewSHS = (TextView) getView().findViewById(R.id.textViewSHS);
	      viewSHS.setText(formatStat(model.SHS, model.SHSW));
	      TextView viewCBT = (TextView) getView().findViewById(R.id.textViewCBT);
	      viewCBT.setText(formatStat(model.CBT, model.CBTW));
	      TextView viewDEF = (TextView) getView().findViewById(R.id.textViewDEF);
	      viewDEF.setText(formatStat(model.DEF, model.DEFW));
	      TextView viewPR = (TextView) getView().findViewById(R.id.textViewPR);
	      viewPR.setText(model.PR);
	      //TextView viewLP = (TextView) getView().findViewById(R.id.textViewLP);
	      //viewLP.setText(formatStat(model.LP, model.LPW));
	      TextView viewFTH = (TextView) getView().findViewById(R.id.textViewFTH);
	      viewFTH.setText(formatStat(model.FTH, model.FTHW));
	      TextView viewCMD = (TextView) getView().findViewById(R.id.textViewCMD);
	      viewCMD.setText(model.CMD);
   }
   
   
   public void setModelById(Integer id) {
	  // Close all previous tooltips 
	  ToolTipManager.CloseOpenedToolTip(null);
	  Model model = m_modelList.get(id);
	  setStatTable(model);
	  View currView = getView();
	  
	  final ImageView modelImg = (ImageView)getView().findViewById(R.id.modelImg);
	  int resId = ((Context)getActivity()).getResources().getIdentifier("i" + String.valueOf(model.getId()), "drawable", "org.helldorado.companybuilder");
	  modelImg.setImageResource(resId); 
	  
	  final ImageView factionImg = (ImageView)currView.findViewById(R.id.factionImg);
	  int resFactionId = ((Context)getActivity()).getResources().getIdentifier("i" + String.valueOf(model.getFaction()), "drawable", "org.helldorado.companybuilder");
	  factionImg.setImageResource(resFactionId); 	  
	  	  
	  String keywords = "";
	  keywords += UnitNature.getSpeciesById(model.getSpecies()) + ", ";
	  keywords += UnitNature.getGenderById(model.getGender()) + ", ";
	  keywords += UnitNature.getReligionById(model.getReligion()) + ", ";
	  String infernalist = UnitNature.getInfernalistById(model.getInfernalist());
	  if (infernalist.compareTo("No Infernalist") != 0){
		  keywords += infernalist + ", "; 
	  }  
	  keywords += model.getLimit();
	  
	  TextView viewKeywords = (TextView) getView().findViewById(R.id.modelKeywords);
	  viewKeywords.setText(keywords);
//	  TextView viewFaction = (TextView) getView().findViewById(R.id.faction);
//	  viewFaction.setText(UnitNature.getFactionById(model.getFaction()));
//	  
//	  TextView viewRank = (TextView) getView().findViewById(R.id.rank);
//	  viewRank.setText(UnitNature.getRankById(model.getRank()));
	  
	  
	  Integer i = 0;
	  TIPD state = State.getStateById(23000);
	  
	  Activity act = getActivity();
	  Context ctx = (Context)act;	  
	  LinearLayout aosaRegionAbilities = (LinearLayout) getView().findViewById(R.id.AOSARegionAbilities);
	  LinearLayout aosaRegionOrders = (LinearLayout) getView().findViewById(R.id.AOSARegionOrders);
	  LinearLayout aosaRegionSpells = (LinearLayout) getView().findViewById(R.id.AOSARegionSpells);
	  aosaRegionAbilities.removeAllViews();
	  aosaRegionOrders.removeAllViews();
	  aosaRegionSpells.removeAllViews();
	  
	  TIPDAdapter tipdAdapter = new TIPDAdapter(ctx, currView);
	  WeaponAdapter weaponAdapter = new WeaponAdapter(ctx, currView);
	  List<TIPD> abilities = model.getAbilities();
	  if (abilities != null)
	  {
		  aosaRegionAbilities.setVisibility(View.VISIBLE);
		  tipdAdapter.AddTIPDsToLayout(abilities, "Abilities: ", aosaRegionAbilities, ", ");
	  }
	  else
	  {
		  aosaRegionAbilities.setVisibility(View.GONE);
	  }
	  
	  List<TIPD> orders = model.getOrders();
	  if (orders != null)
	  {
		  aosaRegionOrders.setVisibility(View.VISIBLE);
		  tipdAdapter.AddTIPDsToLayout(orders, "Orders: ", aosaRegionOrders, ", ");
	  }
	  else
	  {
		  aosaRegionOrders.setVisibility(View.GONE);
	  }
	  
	  List<TIPD> spells = model.getSpells();
	  if (spells != null)
	  {
		  aosaRegionSpells.setVisibility(View.VISIBLE);
		  tipdAdapter.AddTIPDsToLayout(spells, "Spells: ", aosaRegionSpells, ", ");
	  }
	  else
	  {
		  aosaRegionSpells.setVisibility(View.GONE);
	  }

	  LinearLayout weaponsLayout = (LinearLayout) getView().findViewById(R.id.weapons);
	  List<Weapon> weapons = model.getWeapons();
	  List<View> weaponViews = new ArrayList<View>(3);
	  weaponViews.add(getView().findViewById(R.id.weapon1));
	  weaponViews.add(getView().findViewById(R.id.weapon2));
	  weaponViews.add(getView().findViewById(R.id.weapon3));
	  
	  if (weapons != null)
	  {
		  weaponsLayout.setVisibility(View.VISIBLE);
		  Iterator<Weapon> it = weapons.iterator();
		  for (View weaponView : weaponViews){
			  if (it.hasNext()){
				  Weapon weapon = it.next();
				  weaponAdapter.SetWeapon(weapon, weaponView, tipdAdapter);
				  weaponView.setVisibility(View.VISIBLE);
			  }
			  else {
				  weaponView.setVisibility(View.INVISIBLE);				  
			  }				 
		  }
	  }
	  else
	  {
		  weaponsLayout.setVisibility(View.GONE);
	  }
	  
      android.support.v7.widget.GridLayout lifePointsGrid = 
    		  (android.support.v7.widget.GridLayout)getView().findViewById(R.id.lifePointsGrid);
      
      if (m_lifePointViews.size() == 0)
      {
	      ImageView tmp = null;
	      for(int k=0; k<((ViewGroup)lifePointsGrid).getChildCount(); ++k) {
	    	  tmp = (ImageView)((ViewGroup)lifePointsGrid).getChildAt(k);
	    	  if (tmp != null) {
	    		  m_lifePointViews.add(tmp);  
	    	  }
	      }
      }
      
      int lifePoints = model.getLifePoints();
      int maxLifePoints = model.getMaxLifePoints();
      int woundedLifePoints = model.getWoundedLifePoints();
      
      for(int k=1; k<m_lifePointViews.size(); ++k){
    	  if (k > maxLifePoints){
    		  (m_lifePointViews.get(k)).setVisibility(View.INVISIBLE);
    	  }
    	  else
    	  {
    		  String prefix = "";
    		  if (lifePoints >= k)
    		  {
    			  prefix = "n";
    		  }
    		  if (k <= woundedLifePoints){
    			  
        		  int lpId = ctx.getResources().getIdentifier(prefix + "cw" + String.valueOf(k), "drawable", "org.helldorado.companybuilder");
    				//String imgUrl = "drawable://" + String.valueOf(resId);
        		  (m_lifePointViews.get(k)).setImageResource(lpId);
        	  }
    		  else
    		  {
    			  int lpId = ctx.getResources().getIdentifier(prefix + "c" + String.valueOf(k), "drawable", "org.helldorado.companybuilder");
    			  (m_lifePointViews.get(k)).setImageResource(lpId);
    		  }
    		  (m_lifePointViews.get(k)).setVisibility(View.VISIBLE);
    	  }
    	  
      }
      int h = 0;
	   // Different IDs to get the expected behaviour as radio group
	   //
	    
	   // Add the button to the group 
	   //layout.addView(tmp);



	  //	  LinearLayout ll = (LinearLayout) getView().findViewById(R.id.abilitiesRow);
//	  ll.removeAllViews();
//	  m_abilityViews.clear();
//
//	  for (int i1 = 0; i1 < numAbilities; i1++) {
//	      // create a new textview
//	      final TextView rowTextView = new TextView(ctx);
//	      
//	      // set some properties of rowTextView or something
//	      String txt = abilities.get(i1).getTitle();
//	      if (i1 < (numAbilities - 1)){
//	    	  txt += ", ";
//	      }
//	      rowTextView.setText(txt);
//
//	      // add the textview to the linearlayout
//	      ll.addView(rowTextView);
//	      addToolTip(rowTextView, layout);
//	      // save a reference to the textview for later
//	      m_abilityViews.add(rowTextView);
//	  }
	  
   } 
   
}
